package com.hqyj.controller;

import com.hqyj.pojo.TbEstateManager;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @PostMapping("/login")
    public HashMap<String, Object> login(@RequestBody TbEstateManager estateManager, HttpSession session) {
        HashMap<String, Object> map = new HashMap<>();
        // 1. 从Shiro框架中，获取一个Subject对象，代表当前会话的用户
        Subject subject = SecurityUtils.getSubject();
        // 2. 认证subject的身份
        // 2.1 封装要认证的身份信息
        AuthenticationToken token = new UsernamePasswordToken(estateManager.getLoginName(), estateManager.getPassword());
        // 2.2 认证：认证失败，抛异常
        try {
            subject.login(token);
            map.put("info", "登录成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("info", "用户名或密码错误");
        }
        return map;
    }

    @PostMapping("/logout")
    public HashMap<String, Object> logout(@RequestHeader("X-Token") String token){
        HashMap<String, Object> map = new HashMap<>();
        SecurityUtils.getSubject().logout();
        map.put("info", "登出成功");
        return map;
    }
}
